package com.pingan.haofang.searchcloud.common.rpc;

import java.lang.reflect.Type;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pingan.haofang.searchcloud.common.exception.SystemException;

public class DataFetchResponseParser implements RPCResponseParser {

    static Logger LOG = LoggerFactory.getLogger(DataFetchResponseParser.class);

    @Override
    public Object parse(JsonParser parser, Gson gson, String responseBody, RPCConfigProperties config, Type type) {
        JsonObject response = (JsonObject) parser.parse(responseBody);
        if (response == null) {
            LOG.error("rpc response parse error, location:{}, response:{}", config.getUrl(), responseBody);
            throw new SystemException(config.getDefaultErrorMessage());
        }
        JsonObject resultObj = (JsonObject) response.get("result");
        if (resultObj == null) {
            LOG.error("rpc response parse error, location:{}, response:{}", config.getUrl(), responseBody);
            throw new SystemException(config.getDefaultErrorMessage());
        }
        JsonElement code = resultObj.get("errorCode");
        if (code == null) {
            LOG.error("rpc response parse error, location:{}, response:{}", config.getUrl(), responseBody);
            throw new SystemException(config.getDefaultErrorMessage());
        }
        JsonElement message = resultObj.get("errorMessage");
        if (StringUtils.isNotBlank(config.getSuccessCode())) {
            if (!config.getSuccessCode().equals(code.getAsString())) {
                LOG.error("rpc response parse error, location:{}, response:{}", config.getUrl(), responseBody);
                String errMessage = config.getDefaultErrorMessage();
                if (message != null && StringUtils.isNotBlank(message.getAsString())) {
                    errMessage = message.getAsString();
                }
                throw new SystemException(code.getAsString(), errMessage);
            }
        }
        JsonElement data = resultObj.get("datas");
        return gson.fromJson(data, type);
    }

}
